﻿using System;
using System.IO;
using UnityEditor;
using UnityEngine;

public class AutoSetAudioFormat : AssetPostprocessor
{
    private void OnPreprocessAudio()
    {
        AudioImporter audioImporter = (AudioImporter)assetImporter;
        AudioImporterSampleSettings audioSetting = audioImporter.defaultSampleSettings;
        audioSetting.sampleRateOverride = 22050;
        audioImporter.SetOverrideSampleSettings("WebGL", audioSetting);
        audioImporter.forceToMono = true;
        audioImporter.preloadAudioData = true;

        if (assetPath.Contains("Assets/Game/Repository/Audios/Music"))
        {
            //加载方式选择
            audioSetting.loadType = AudioClipLoadType.Streaming;
            //压缩方式选择
            audioSetting.compressionFormat = AudioCompressionFormat.Vorbis;
            //设置播放质量
            audioSetting.quality = 0.1f;
        }
        else if (assetPath.Contains("Assets/Game/Repository/Audios/Sounds"))
        {
            //加载方式选择
            audioSetting.loadType = AudioClipLoadType.DecompressOnLoad;
            //压缩方式选择
            audioSetting.compressionFormat = AudioCompressionFormat.PCM;
            //设置播放质量
            audioSetting.quality = 0.6f;

        }
        //优化采样率
        audioSetting.sampleRateSetting = AudioSampleRateSetting.OptimizeSampleRate;
        audioImporter.defaultSampleSettings = audioSetting;


    }

    private void OnPostprocessAudio(AudioClip arg)
    {
        AudioImporter audioImporter = (AudioImporter) assetImporter;
        string dirName = Path.GetDirectoryName(assetPath);
        string name = Path.GetFileNameWithoutExtension(assetPath);
        string folderStr = Path.GetFileName(dirName);
        Debug.Log(assetPath);
        Debug.Log(dirName);
        Debug.Log(name);
        Debug.Log(folderStr);
        string fullPath = $"{Application.dataPath.Replace("Assets", "")}/{assetPath}";
        if (assetPath.Contains("Assets/AssetsHotfix/Repository/Audios/Music"))
        {
            if (assetPath.ToLower().Contains("wav")
                || assetPath.ToLower().Contains("ogg")
            )
            {
                string namePath = fullPath.Replace("wav", "mp3");
                namePath = namePath.Replace("ogg", "mp3");
                File.Move(fullPath, namePath);
            }
        }
        else
        {
            /*if (assetPath.ToLower().Contains("mp3") 
                || assetPath.ToLower().Contains("ogg")
            )
            {
                string namePath = fullPath.Replace("mp3", "wav");
                namePath = namePath.Replace("ogg", "wav");
                File.Move(fullPath,namePath);
            }*/
        }
    }

}